<template>
<a-upload
  :action="action"
  :headers="{
    'Authorization': `Bearer ${accessToken}`
  }"
  @change="onChange"
>
  <template #upload-button>
    <a-image
      v-if="url"
      :preview="false"
      :width="width"
      :height="height"
      :src="url"
      :fit="fit"
    >
    </a-image>
    <div v-else class="arco-upload-picture-card" :style="{width: width + 'px', height: height + 'px'}">
      <div class="arco-upload-picture-card-text">
        <IconPlus />
      </div>
    </div>
  </template>
</a-upload>
</template>

<script>
import { getAccessToken } from "@/utils/auth";

export default {
  name: "EUploadImage",
  props: {
    accept: {
      type: String,
      default: 'image/*'
    },
    url: {
      type: String,
      default: '',
      required: false
    },
    width: {
      type: Number,
      default: 200,
      required: false
    },
    height: {
      type: Number,
      default: 200,
      required: false
    },
    fit: {
      type: String,
      default: 'cover'
    }
  },
  emits: ['update:url'],
  computed: {
    accessToken: () => getAccessToken(),
    action: () => `${import.meta.env.VITE_API_BASE_URL}/storage/upload`
  },
  methods: {
    onChange(_, currentFile) {
      if (currentFile.status === 'done') {
        this.$emit('update:url', currentFile.response?.data?.url)
      } else {
        this.$emit('update:url', currentFile.url)
      }
    }
  }
}
</script>

<style scoped>
</style>